package com.weirong.smartvault.backservice.util.table;

import com.weirong.smartvault.common.tools.constant.AuthorityConstant;
import com.weirong.smartvault.common.tools.spring.context.SpringContextUtil;
import com.weirong.smartvault.backservice.util.common.ListTool;
import com.weirong.smartvault.dao.AuthorityRepository;
import com.weirong.smartvault.backservice.entity_model.AuthorityModel;

import java.lang.reflect.InvocationTargetException;
import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * User: kfeb4
 * Date: 2017/12/29
 * Time: 15:59
 */
public class AuthorityTable {
    static AuthorityRepository authorityRepository = SpringContextUtil.getBean(AuthorityRepository.class);

    public static Table buildByRootNode(Collection<Integer> extendsRoot) throws InvocationTargetException, NoSuchMethodException, InstantiationException, IllegalAccessException {
        //extendsRoot是要展开的Id号
        List<AuthorityModel> roots = ListTool.cast(authorityRepository.findAllByIdIn(extendsRoot), AuthorityModel.class);//根节点
        Set<AuthorityModel> goalNode = new HashSet<>();
        for (AuthorityModel root : roots) {
            goalNode.addAll(root.getAll());
        }
        goalNode.addAll(ListTool.cast(authorityRepository.findAllByGrade(1), AuthorityModel.class));//添加其他未展开节点

        List<Tree<AuthorityModel>> rts = AuthorityTree.buildTreeWithAllSon(goalNode);
        for (Tree<AuthorityModel> t : rts) {
            Boolean contains = false;
            t.additionInf = "";
            for (Integer s : extendsRoot) {
                if (s != t.obj.getId()) {
                    t.additionInf += s + ",";
                } else
                    contains = true;
            }
            if (!contains)
                t.additionInf += t.obj.getId();
            t.obj.checked = contains;
        }
        Table table = new Table(AuthorityConstant.lv + 2);
        setTree(table, rts, 0);

        List<Tree<AuthorityModel>> endpoints = ListTool.collect(rts, Tree::getEndPoints);
        for (Tree<AuthorityModel> point : endpoints){
            table.setOne(AuthorityConstant.lv + 1, point.obj.getRemark(),1);
            table.setOne(AuthorityConstant.lv, point.obj.getUrl(),1);
        }
        table.freeze();
        return table;
    }

    public static Table buildTable(Collection<AuthorityModel> m){
        // 获取所有得到叶节点的权限
        Table table = new Table(AuthorityConstant.lv);
        List<Tree<AuthorityModel>> roots = AuthorityTree.buildTreeWithAllSon(m);
        setTree(table, roots, 0);
        return table;
    }

    static void setTree(Table<AuthorityModel> table, List<Tree<AuthorityModel>> nodes, Integer x) {
        for (Tree<AuthorityModel> node : nodes) {
            table.setOne(x, node.obj.getName(), node.width(), node.obj, node.additionInf);
            setTree(table, node.sons, x + 1);
        }
    }
}
